package wens.pig.dhm.formplugin.patrolscheme;

import dm.jdbc.util.StringUtil;
import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.dynamicobject.DynamicObjectType;
import kd.bos.entity.api.ApiResult;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.tree.TreeNode;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.container.Tab;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.control.TreeView;
import kd.bos.form.control.events.TabSelectEvent;
import kd.bos.form.control.events.TabSelectListener;
import kd.bos.form.control.events.TreeNodeClickListener;
import kd.bos.form.control.events.TreeNodeEvent;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.HyperLinkClickEvent;
import kd.bos.form.events.HyperLinkClickListener;
import kd.bos.form.field.BasedataEdit;
import kd.bos.form.field.events.BeforeF7SelectEvent;
import kd.bos.form.field.events.BeforeF7SelectListener;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import org.apache.commons.lang3.StringUtils;
import wens.pig.base.common.consts.dhm.*;
import wens.pig.base.common.enums.BillStatusEnum;
import wens.pig.base.common.enums.EnvPlanExeStatusEnum;
import wens.pig.base.utils.*;

import java.util.*;
import java.util.stream.Collectors;



/**
 * 巡查工作台页面插件
 * coyle
 */
public class PatrolPlatFormPlugin extends AbstractFormPlugin implements BeforeF7SelectListener , TabSelectListener, TreeNodeClickListener , HyperLinkClickListener {
    private static final String EXESTATE = "wens_exestate_head";
    /**
     * 数状图
     */
    private final static String TREEVIEWAP_NEGA = "wens_treeviewap_nega";
    private final static String TREEVIEWAP_PAT = "wens_treeviewap_pat";
    private final static String TABLE = "wens_tabap_nega";
    private final static String WENS_PATROL_TYPE_ENTRY = "wens_zonetype_nage";
    private final static String WENS_SDATE_NEGA = "wens_sdate_nega";
    private final static String WENS_EDATE_NEGA = "wens_edate_nega";
    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        BasedataEdit
        f7cont = this.getControl("wens_twoclass");
        f7cont.addBeforeF7SelectListener(this);
        f7cont = this.getControl("wens_role_mul");
        f7cont.addBeforeF7SelectListener(this);
        f7cont = this.getControl("wens_rolequery_pat");
        f7cont.addBeforeF7SelectListener(this);
        f7cont = this.getControl("wens_rolequery_nage");
        f7cont.addBeforeF7SelectListener(this);
        f7cont = this.getControl("wens_rolequery_rectpl");
        f7cont.addBeforeF7SelectListener(this);
        f7cont = this.getControl("wens_rolequery_rect");
        f7cont.addBeforeF7SelectListener(this);


        Tab tabap = this.getControl(TABLE);
        tabap.addTabSelectListener(this);
        tabap = this.getControl("wens_tabap_pat");
        tabap.addTabSelectListener(this);
        tabap = this.getControl("wens_tabap");
        tabap.addTabSelectListener(this);
        //非生产线
        TreeView treeView = this.getView().getControl(TREEVIEWAP_NEGA);
        treeView.addTreeNodeClickListener(this);
        //非生产线
        treeView = this.getView().getControl(TREEVIEWAP_PAT);
        treeView.addTreeNodeClickListener(this);


    }


    /**
     * 设置数状图
     */
    private void setTreeView() {
        TreeView treeView = getControl(TREEVIEWAP_NEGA);
        List<TreeNode> list = new ArrayList<TreeNode>();
        //最上级
        list.add(new TreeNode(null, "001", "全部"));
        //第二级
        QFilter baseDataQFilter = QFilterUtils.getBaseDataQFilter();
        QFilter one = new QFilter("1", QCP.equals, "1");
        one.and(baseDataQFilter);
        one.and(PatrolregionConstant.PARENT, QCP.equals, "");
        DynamicObject[] onePatr = BusinessDataServiceHelper.load(PatrolregionConstant.FORMBILLID, PatrolregionConstant.ALLPROPERTY, one.toArray());
        for (DynamicObject item : onePatr) {
            String oneId = item.getString(PatrolregionConstant.ID);
            String oneName = item.getString(PatrolregionConstant.NAME);
            list.add(new TreeNode("001", oneId, oneName));
            //二级分类
            QFilter two = new QFilter("1", QCP.equals, "1");
            two.and(baseDataQFilter);
            two.and(PatrolregionConstant.PARENT + ".id", QCP.equals, oneId);
            DynamicObject[] twoPat = BusinessDataServiceHelper.load(PatrolregionConstant.FORMBILLID, PatrolregionConstant.ALLPROPERTY, two.toArray());
            for (DynamicObject twoItem : twoPat) {
                String twoId = twoItem.getString(PatrolregionConstant.ID);
                String twoName = twoItem.getString(PatrolregionConstant.NAME);
                list.add(new TreeNode(oneId, twoId, twoName));
            }
            this.setPatrolTypeEntry(twoPat);
        }
        treeView.addNodes(list);
        //设置默认展开
        treeView.expand("001");
        Arrays.stream(onePatr).forEach(item -> treeView.expand(item.getString("id")));
    }

    /**
     * 设置区分类分录
     *
     * @param item
     */
    private void setPatrolTypeEntry(DynamicObject[] item) {
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("wens_ztype_en");
        DynamicObjectType entryType = entryEntity.getDynamicObjectType();
        for (DynamicObject treeItem : item) {
            DynamicObject dynamicObject = new DynamicObject(entryType);
            dynamicObject.set(WENS_PATROL_TYPE_ENTRY, treeItem);
            entryEntity.add(dynamicObject);
        }
    }


    @Override
    public void afterBindData (EventObject e) {
        //查询巡查计划
        this.getView().setVisible(false,"wens_flex_pat","wens_flex_nage");


    }

    /**
     * 按巡查小组和巡查日期查询
     * 负面清单
     */
    private void queryNegativeList() {
        IDataModel model = this.getModel();
        model.deleteEntryData("wens_line_nageen");
        model.deleteEntryData("wens_ztype_en");
        DynamicObject obj = model.getDataEntity(true);
        String org = obj.getString("wens_org.id");
        QFilter qFilter = new QFilter("org",QCP.equals,org); //z组织
        //巡查日期
        Date startdate = obj.getDate(WENS_SDATE_NEGA);
        Date enddate = obj.getDate(WENS_EDATE_NEGA);
        if(null != startdate && null!= enddate){
            qFilter.and("wens_date", QCP.large_equals, DateUtil.getDateStartTime(startdate));
            qFilter.and("wens_date", QCP.less_equals,DateUtil.getDateEndTime(enddate));
        }
        DynamicObjectCollection role = (DynamicObjectCollection) obj.getDynamicObjectCollection("wens_rolequery_nage");
        if (role != null && role.size() != 0) {
            List<String> roleList = role.stream().map(item -> item.getString("fbasedataid.id")).collect(Collectors.toList());
            qFilter.and("wens_role", QCP.in, roleList);
        }
//        String exestate = obj.getString("wens_exestate_head");
//        if(StringUtils.isNotBlank(exestate)){
//            qFilter.and("wens_exestate_head", QCP.equals, exestate);
//        }

        //执行状态
        String isplan = obj.getString("wens_exestatequery_nage");
        if(StringUtils.isNotBlank(isplan)){
            if(StringUtils.equals(isplan,"1")){
                qFilter.and(NegativeInventoryConstant.WENS_PLANDETAILS, QCP.is_notnull, "");
            }else{
                qFilter.and(NegativeInventoryConstant.WENS_PLANDETAILS, QCP.is_null, "");
            }
        }
   /*     //巡查计划数据;
        HashMap<String, Integer> planMap = queryPlanDataFromPatTab();
        int comCount = 0; //已完成巡查位点数
        int unqualCount = 0; //不合格位点数
        int recedCount = 0; //已整改位点数
        int lineUnquCount = 0; //生产区不合格点位数
        int unlineUnquCount = 0; //非生产区不合格点位数*/


        //生产线类型分类
        DynamicObjectCollection prodEntry = model.getEntryEntity("wens_line_nageen");
        DynamicObjectType prodEntryType = prodEntry.getDynamicObjectType();
        //区域分类
        DynamicObjectCollection parEntry = model.getEntryEntity("wens_ztype_en");
        DynamicObject[] billObjs = BusinessDataServiceHelper.load(NegativeInventoryConstant.FORMBILLID, NegativeInventoryConstant.ALLPROPERTY, qFilter.toArray());
        for (DynamicObject item : billObjs) {
            //巡查计划分录
//            DynamicObject sambillno = item.getDynamicObject(NegativeInventoryConstant.BILLNO);
//            if(sambillno != null){
//                continue;
//            }

            //生产线
            DynamicObject prouctLine = item.getDynamicObject(NegativeInventoryConstant.WENS_LINE);
            //区域分类
            DynamicObject three = item.getDynamicObject(NegativeInventoryConstant.WENS_THREE);
            //巡查位点
            DynamicObject site = item.getDynamicObject(NegativeInventoryConstant.WENS_SITE);
            //具体位置
            String siteDetails = item.getString(NegativeInventoryConstant.WENS_SITEDETAILS);
            //巡查人员
            DynamicObject sampUser = item.getDynamicObject(NegativeInventoryConstant.WENS_PATROL_USER);
            //分录id
            Object pkValue = item.getPkValue();
            if (prouctLine != null) {
                //1、判断当前计划分录生产线是否已经存在
                List<DynamicObject> prouctId = prodEntry.stream().filter(itemId ->
                        StringUtil.equals(itemId.getString( "wens_line_nega.id"),
                                prouctLine.getString("id"))).collect(Collectors.toList());
                DynamicObject dynamicObject = null;
                if (prouctId.size() == 0) {
                    //类型：生产线 新增生产线单据体
                    dynamicObject = new DynamicObject(prodEntryType);
                    dynamicObject.set("wens_line_nega", prouctLine);
                    prodEntry.add(dynamicObject);
                } else {
                    dynamicObject = prouctId.get(0);
                }
                DynamicObjectCollection prEntryDetails = dynamicObject.getDynamicObjectCollection("wens_line_suben");
                //猪舍
                DynamicObject pigSty = item.getDynamicObject(NegativeInventoryConstant.WENS_PIGSTY);
                //单元+栏位
                String place = item.getString(NegativeInventoryConstant.WENS_PIGFIELD);
                DynamicObject proDetails = prEntryDetails.addNew();
                proDetails.set("wens_picture1", item.getString(NegativeInventoryConstant.WENS_PATROL_IMG1));
                proDetails.set("wens_picture2", item.getString(NegativeInventoryConstant.WENS_PATROL_IMG2));
                proDetails.set("wens_picture3", item.getString(NegativeInventoryConstant.WENS_PATROL_IMG3));
                proDetails.set("wens_prodesc_nega", item.getString(NegativeInventoryConstant.WENS_PROBLEM));
                proDetails.set("wens_result_nega", item.getString(NegativeInventoryConstant.WENS_PATROL_RESULT));
                proDetails.set("wens_pers_nega", sampUser);
                proDetails.set("wens_plancdate_nega", item.getDate(NegativeInventoryConstant.WENS_COMPLETIONDATE));
                proDetails.set("wens_pigsty_nega", pigSty);
                proDetails.set("wens_cell_nega", place);
                proDetails.set("wens_zonetype_nega", three);
                proDetails.set("wens_site_nega", site);
                proDetails.set("wens_loca_nega", siteDetails);
                proDetails.set("wens_exedate_nega",item.getDate(NegativeInventoryConstant.WENS_DATE));
                proDetails.set("wens_patrol_nega",item.getString(NegativeInventoryConstant.WENS_PATROL_RECORD+".billno"));
                proDetails.set("wens_rectpla_nega", item.getString(NegativeInventoryConstant.WENS_PLANDETAILS+".billno"));//整改计划;
                proDetails.set("wens_rect_nega", item.getString(NegativeInventoryConstant.WENS_RECORDDETAILS+".billno"));

                String issolve = item.getString(NegativeInventoryConstant.WENS_ISSOLVE);
                if(StringUtils.equals(issolve,"0")){
                    proDetails.set("wens_solvedate_nega", item.getDate(NegativeInventoryConstant.WENS_BUSINESSDATE ));
                }
                proDetails.set("wens_issolve_nega", issolve);

            } else {
                //二级分类
                DynamicObject twoClass = item.getDynamicObject(NegativeInventoryConstant.WENS_CLASSTWO);
                if(null == twoClass){
                    continue;
                }
                //类型：非生产线
                //1、判断当前计划分录生产线是否已经存在
                List<DynamicObject> patrolType = parEntry.stream().filter(itemId ->
                        StringUtil.equals(itemId.getString(WENS_PATROL_TYPE_ENTRY + ".id"),
                                twoClass.getString("id"))).collect(Collectors.toList());
                DynamicObject dynamicObject = new DynamicObject(parEntry.getDynamicObjectType());
                if (patrolType.size() > 0) {
                    dynamicObject = patrolType.get(0);
                }else {
                    dynamicObject.set("wens_zonetype_nage",twoClass);
                    parEntry.add(dynamicObject);
                }
                DynamicObjectCollection patDatails = dynamicObject.getDynamicObjectCollection("wens_uline_suben");
                DynamicObject proDetails = patDatails.addNew();
                proDetails.set("wens_picture1_u", item.getString(NegativeInventoryConstant.WENS_PATROL_IMG1));
                proDetails.set("wens_picture2_u", item.getString(NegativeInventoryConstant.WENS_PATROL_IMG2));
                proDetails.set("wens_picture3_u", item.getString(NegativeInventoryConstant.WENS_PATROL_IMG3));
                proDetails.set("wens_prodesc_nega_u", item.getString(NegativeInventoryConstant.WENS_PROBLEM));
                proDetails.set("wens_result_nega_u", item.getString(NegativeInventoryConstant.WENS_PATROL_RESULT));
                proDetails.set("wens_pers_nega_u", sampUser);
                proDetails.set("wens_plancdate_nega_u", item.getDate(NegativeInventoryConstant.WENS_COMPLETIONDATE));
                proDetails.set("wens_zonetype_nega_u", three);
                proDetails.set("wens_site_nega_u", site);
                proDetails.set("wens_loca_nega_u", siteDetails);
                proDetails.set("wens_exedate_nega_u",item.getDate(NegativeInventoryConstant.WENS_DATE));
                proDetails.set("wens_patrol_nega_u",item.getString(NegativeInventoryConstant.WENS_PATROL_RECORD+".billno"));
                proDetails.set("wens_rectpla_nega_u", item.getString( NegativeInventoryConstant.WENS_PLANDETAILS+".billno"));//整改计划;
                proDetails.set("wens_rect_nega_u", item.getString(NegativeInventoryConstant.WENS_RECORDDETAILS+".billno"));
                String issolve = item.getString(NegativeInventoryConstant.WENS_ISSOLVE);
                if(StringUtils.equals(issolve,"0")){
                    proDetails.set("wens_solvedate_nega_u", item.getDate(NegativeInventoryConstant.WENS_BUSINESSDATE ));
                }
                proDetails.set("wens_issolve_nega_u", issolve);
            }
        }
        //planMap
       /* model.setValue("wens_patcom_nega",  planMap.get("wens_plan_plan"));
        model.setValue("wens_unqual_nega", ); //不合格位点;
        model.setValue("wens_reced_nega",unqualCount); //已整改位点数
        model.setValue("wens_llineunqu_nega",lineUnquCount);//生产区不合格点位数
        model.setValue("wens_unli_unqu_nega",unlineUnquCount); //非生产区不合格点位数*/
        //设置区域分类数状图
        this.setTreeView(1);

        //清除缓存
        this.getModel().updateEntryCache(prodEntry);
        this.getView().updateView("wens_line_nageen");
        this.getModel().updateEntryCache(parEntry);
        this.getView().updateView("wens_ztype_en");
    }



    /**
     * 根据巡查记录页签
     * 查询巡查计划
     */
    private  HashMap<String,Integer> queryPlanDataFromPatTab(){
        HashMap<String,Integer> map = new HashMap();
        IDataModel model = this.getModel();
        DynamicObject obj = model.getDataEntity(true);
        String org = obj.getString("wens_org.id");
        QFilter qFilter = new QFilter("org",QCP.equals,org); //z组织
        //巡查日期
//        Date startdate = obj.getDate("wens_sdate_pat");
//        Date enddate = obj.getDate("wens_edate_pat");

        qFilter.and("wens_startdate", QCP.less_equals,DateUtil.getDateEndTime(new Date()) );
        qFilter.and("wens_enddate", QCP.large_equals,DateUtil.getDateStartTime(new Date()));
        DynamicObjectCollection role = (DynamicObjectCollection) obj.getDynamicObjectCollection("wens_rolequery_pat");
        if (role != null && role.size() != 0) {
            List<String> roleList = role.stream().map(item -> item.getString("fbasedataid.id")).collect(Collectors.toList());
            qFilter.and("wens_role", QCP.in, roleList);
        }
        //计划巡查位点数
        int planCount =  0;
        //已完成巡查位点数
        int comCount = 0;
        //待巡查位点数
        int planunCount = 0;
        //超期未执行位点数
        int uncomCount  = 0;
        DynamicObject[] load = BusinessDataServiceHelper.load(PatrolPlanConstant.FORMBILLID, PatrolPlanConstant.ALLPROPERTY, qFilter.toArray());
        for( DynamicObject planObj : load ){
            DynamicObjectCollection planEnCol = planObj.getDynamicObjectCollection(PatrolPlanConstant.ENTRYENTITYID_WENS_ENTRYDETAIL);
            for(DynamicObject planEn :  planEnCol){
                //计算数据;
                //计划巡查位点数
                if(!StringUtils.equals(planObj.getString("wens_exestate_head"),EnvPlanExeStatusEnum.CANCEL.getValue())){
                    ++planCount;
                }
                //已完成巡查位点数
                if(!ObjectUtil.isNull(planEn.getString(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO))){
                    ++comCount;
                }
                //待巡查位点数
                if(StringUtils.equals(planObj.getString("wens_exestate_head"),EnvPlanExeStatusEnum.EXEING.getValue()) &&
                        ObjectUtil.isNull(planEn.getString(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO))){
                    ++planunCount;
                }
                //超期未执行位点数
                if(StringUtils.equals(planObj.getString("wens_exestate_head"),EnvPlanExeStatusEnum.UNCOM.getValue()) &&
                        ObjectUtil.isNull(planEn.getString(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO))){
                    ++uncomCount;
                }
            }
        }
        map.put("wens_plan_plan",planCount);
        map.put("wens_com_plan",comCount);
        map.put("wens_planun_plan",planunCount);
        map.put("wens_planuncom_plan",uncomCount);
        return  map;
    }

    /**
     * 查询巡查记录
     * map 放过来参数
     */
    private void queryPatrolList(Map map) {
        IDataModel model = this.getModel();
        model.deleteEntryData("wens_line_paten");
        model.deleteEntryData("wens_ztype_paten");
        DynamicObject obj = model.getDataEntity(true);
        String org = obj.getString("wens_org.id");
        QFilter qFilter = new QFilter("org",QCP.equals,org); //z组织
        //巡查日期
        Date startdate = obj.getDate("wens_sdate_pat");
        Date enddate = obj.getDate("wens_edate_pat");
        if(null != startdate && null!= enddate){
            qFilter.and("wens_patrol_date", QCP.large_equals, DateUtil.getDateStartTime(startdate));
            qFilter.and("wens_patrol_date", QCP.less_equals,DateUtil.getDateEndTime(enddate));
        }
        DynamicObjectCollection role = (DynamicObjectCollection) obj.getDynamicObjectCollection("wens_rolequery_pat");
        if (role != null && role.size() != 0) {
            List<String> roleList = role.stream().map(item -> item.getString("fbasedataid.id")).collect(Collectors.toList());
            qFilter.and("wens_role", QCP.in, roleList);
        }
        //单据状态
        String billStatus = obj.getString("wens_statusquery_pat");
        if(StringUtils.isNotBlank(billStatus)){
            qFilter.and("billstatus", QCP.equals, billStatus);
        }
        //巡查结果
        String exestate = obj.getString("wens_result_pat");
        if(StringUtils.isNotBlank(exestate)){
            qFilter.and("wens_patrol_result", QCP.equals, exestate);
        }
        //执行状态 wens_issolve
        String result = obj.getString("wens_exestatequery_pat");
        if(StringUtils.isNotBlank(result) && !StringUtils.equals(result,"2")){
            if(StringUtils.equals(result,"1")){ //计划中
                qFilter.and("wens_issolve", QCP.in,new String[]{"","1"});
            }else{
                qFilter.and("wens_issolve", QCP.equals, result);
            }
        }
        //已整改过滤;
        boolean isRectified = false;
        if(null != map && map.containsKey("rectified")){
            isRectified = true;
        }
        //巡查计划数据;
        HashMap<String, Integer> planMap = queryPlanDataFromPatTab();
        //不合格位点数
        int   unqualCount  = 0;
        //生产区不合格点位数
        int  lineUnquCount = 0;
        //非生产区不合格点位数
        int  unlineUnquCount = 0;
        //已整改位点数wens_reced_pat
        int  recedCount = 0;
        //生产线类型分类
        DynamicObjectCollection prodEntry = model.getEntryEntity("wens_line_paten");
        DynamicObjectType prodEntryType = prodEntry.getDynamicObjectType();
        //区域分类
        DynamicObjectCollection parEntry = model.getEntryEntity("wens_ztype_paten");
        DynamicObject[] billObjs = BusinessDataServiceHelper.load(PatrolRecordConstant.FORMBILLID, PatrolRecordConstant.ALLPROPERTY, qFilter.toArray());
        for (DynamicObject item : billObjs) {
            //巡查计划分录
//            DynamicObject sambillno = item.getDynamicObject(NegativeInventoryConstant.BILLNO);
//            if(sambillno != null){
//                continue;
//            }
            String isSolve = ToolUtils.cnulls(item.getString( "wens_issolve"));
            if(StringUtils.equals(isSolve,"0")){
                ++recedCount;
            }
            //已整改
            if(isRectified){
                if(!StringUtils.equals(isSolve,"0")){
                    //0已解决;1未解决
                    continue;
                }
            }
            //生产线
            DynamicObject prouctLine = item.getDynamicObject(PatrolRecordConstant.WENS_PRODUCTLINE);
            //区域分类
            DynamicObject three = item.getDynamicObject(PatrolRecordConstant.WENS_THREE);
            //巡查位点
            DynamicObject site = item.getDynamicObject(PatrolRecordConstant.WENS_SITE);
            //具体位置
            String siteDetails = item.getString(PatrolRecordConstant.WENS_SITEDETAILS);
            //巡查人员
            DynamicObject sampUser = item.getDynamicObject(PatrolRecordConstant.WENS_PATROL_USER);
            //分录id
            Object pkValue = item.getPkValue();
            if (prouctLine != null) {
                //1、判断当前计划分录生产线是否已经存在
                List<DynamicObject> prouctId = prodEntry.stream().filter(itemId ->
                        StringUtil.equals(itemId.getString( "wens_line_pat.id"),
                                prouctLine.getString("id"))).collect(Collectors.toList());
                DynamicObject dynamicObject = null;
                if (prouctId.size() == 0) {
                    //类型：生产线 新增生产线单据体
                    dynamicObject = new DynamicObject(prodEntryType);
                    dynamicObject.set("wens_line_pat", prouctLine);
                    prodEntry.add(dynamicObject);
                } else {
                    dynamicObject = prouctId.get(0);
                }
                DynamicObjectCollection prEntryDetails = dynamicObject.getDynamicObjectCollection("wens_line_patsuben");
                //猪舍
                DynamicObject pigSty = item.getDynamicObject(PatrolRecordConstant.WENS_PIGSTY);
                //单元+栏位
                String place = item.getString(PatrolRecordConstant.WENS_PIGFIELD);
                DynamicObject proDetails = prEntryDetails.addNew();
                DynamicObjectCollection atFile = item.getDynamicObjectCollection(PatrolRecordConstant.WENS_ATTACHMENTFIELD);
                MulBaseDataUtil.setMulBaseDataVal(proDetails,"wens_file_pat",atFile);
                proDetails.set("wens_picture1_pat", item.getString("wens_picture1"));
                proDetails.set("wens_picture2_pat", item.getString("wens_picture2"));
                proDetails.set("wens_picture3_pat", item.getString("wens_picture3"));
                proDetails.set("wens_prodesc_pat", item.getString(PatrolRecordConstant.WENS_PROBLEM));
                proDetails.set("wens_plancdate_pat", item.getDate(PatrolRecordConstant.WENS_COMPLETE_DATE));
                proDetails.set("wens_pigsty_pat", pigSty);
                proDetails.set("wens_cell_pat", place);
                proDetails.set("wens_three_pat", three);
                proDetails.set("wens_site_pat", site);
                proDetails.set("wens_loca_pat", siteDetails);
                proDetails.set("wens_pers_pat", item.getDynamicObject(PatrolRecordConstant.WENS_PATROL_USER));
                proDetails.set("wens_presult_pat", item.getString(PatrolRecordConstant.WENS_PATROL_RESULT));
                proDetails.set("wens_psdate_pat", item.getDate(PatrolRecordConstant.WENS_EXESTARTDATE));
                proDetails.set("wens_pedate_pat", item.getDate(PatrolRecordConstant.WENS_EXEENDDATE));
                proDetails.set("wens_exedate_pat", item.getDate(PatrolRecordConstant.WENS_PATROL_DATE));
                proDetails.set("wens_replan_pat", item.getString(PatrolRecordConstant.WENS_PATROLPLAN+".billno" ));
                proDetails.set("wens_nega_pat", item.getString(PatrolRecordConstant.WENS_NEGATIVE_INVENTORY+".billno"));
                String  negaId= item.getString(PatrolRecordConstant.WENS_NEGATIVE_INVENTORY + ".id");
                if(StringUtils.isNotBlank(negaId)){
                    DynamicObject nagaObj = BusinessDataServiceHelper.loadSingle(negaId, NegativeInventoryConstant.FORMBILLID, NegativeInventoryConstant.WENS_PLANDETAILS);
                    proDetails.set("wens_rectpla_pat",nagaObj.getString(NegativeInventoryConstant.WENS_PLANDETAILS+".billno")); //整改计划从负面清单关联
                }

                proDetails.set("wens_rect_pat", item.getString(PatrolRecordConstant.WENS_RECORDDETAILS+".billno" ));//整改记录
                String  rectId= item.getString(PatrolRecordConstant.WENS_RECORDDETAILS + ".id");//整改记录
                if(StringUtils.isNotBlank(rectId)){
                    DynamicObject rectObj = BusinessDataServiceHelper.loadSingle(rectId, RecordDetailsConstant.FORMBILLID, RecordDetailsConstant.WENS_FILE2);
                    proDetails.set("wens_resfile_pat",rectObj.getDynamicObjectCollection(RecordDetailsConstant.WENS_FILE2)); //文件
                }
                proDetails.set("wens_recpers_pat", item.getDynamicObject(PatrolRecordConstant.WENS_HEAD_USER));
                proDetails.set("wens_issolve_pat", item.getString(PatrolRecordConstant.WENS_ISSOLVE));
                proDetails.set("wens_patid", item.getString(PatrolRecordConstant.ID));
                if(StringUtils.equals(item.getString(PatrolRecordConstant.WENS_PATROL_RESULT),"0")){
                    ++unqualCount ;
                    ++lineUnquCount;//生产区不合格点位数
                }
            } else {
                //二级分类 非生产线
                DynamicObject twoClass = item.getDynamicObject(PatrolRecordConstant.WENS_CLASSTWO);
                if(null == twoClass){
                    continue;
                }
                //类型：非生产线
                //1、判断当前计划分录生产线是否已经存在
                List<DynamicObject> patrolType = parEntry.stream().filter(itemId ->
                        StringUtil.equals(itemId.getString( "wens_zonetype_pat.id"),
                                twoClass.getString("id"))).collect(Collectors.toList());
                DynamicObject dynamicObject = new DynamicObject(parEntry.getDynamicObjectType());
                if (patrolType.size() > 0) {
                    dynamicObject = patrolType.get(0);
                }else {
                    dynamicObject.set("wens_zonetype_pat",twoClass);
                    parEntry.add(dynamicObject);
                }
                DynamicObjectCollection patDatails = dynamicObject.getDynamicObjectCollection("wens_uline_patsuben");
                DynamicObject proDetails = patDatails.addNew();
                DynamicObjectCollection atFile = item.getDynamicObjectCollection(PatrolRecordConstant.WENS_ATTACHMENTFIELD);
                MulBaseDataUtil.setMulBaseDataVal(proDetails,"wens_file_pat_U",atFile);
                proDetails.set("wens_picture1_pat_U", item.getString("wens_picture1"));
                proDetails.set("wens_picture2_pat_U", item.getString("wens_picture2"));
                proDetails.set("wens_picture3_pat_U", item.getString("wens_picture3"));
                proDetails.set("wens_prodesc_pat_U", item.getString(PatrolRecordConstant.WENS_PROBLEM));
                proDetails.set("wens_plancdate_pat_U", item.getDate(PatrolRecordConstant.WENS_COMPLETE_DATE));
                proDetails.set("wens_three_pat_U", three);
                proDetails.set("wens_site_pat_U", site);
                proDetails.set("wens_loca_pat_U", siteDetails);
                proDetails.set("wens_pers_pat_U", item.getDynamicObject(PatrolRecordConstant.WENS_PATROL_USER));
                proDetails.set("wens_presult_pat_U", item.getString(PatrolRecordConstant.WENS_PATROL_RESULT));
                proDetails.set("wens_psdate_pat_U", item.getDate(PatrolRecordConstant.WENS_EXESTARTDATE));
                proDetails.set("wens_pedate_pat_U", item.getDate(PatrolRecordConstant.WENS_EXEENDDATE));
                proDetails.set("wens_exedate_pat_U", item.getDate(PatrolRecordConstant.WENS_PATROL_DATE));
                proDetails.set("wens_replan_pat_U", item.getString(PatrolRecordConstant.WENS_PATROLPLAN+".billno" ));
                proDetails.set("wens_nega_pat_U", item.getString(PatrolRecordConstant.WENS_NEGATIVE_INVENTORY+".billno"));
                String  negaId= item.getString(PatrolRecordConstant.WENS_NEGATIVE_INVENTORY + ".id");
                if(StringUtils.isNotBlank(negaId)){
                    DynamicObject nagaObj = BusinessDataServiceHelper.loadSingle(negaId, NegativeInventoryConstant.FORMBILLID, NegativeInventoryConstant.WENS_PLANDETAILS);
                    proDetails.set("wens_rectpla_pat_U",nagaObj.getString(NegativeInventoryConstant.WENS_PLANDETAILS+".billno")); //整改计划从负面清单关联
                }

                proDetails.set("wens_rect_pat_U", item.getString(PatrolRecordConstant.WENS_RECORDDETAILS+".billno" ));//整改记录
                String  rectId= item.getString(PatrolRecordConstant.WENS_RECORDDETAILS + ".id");//整改记录
                if(StringUtils.isNotBlank(rectId)){
                    DynamicObject rectObj = BusinessDataServiceHelper.loadSingle(rectId, RecordDetailsConstant.FORMBILLID, RecordDetailsConstant.WENS_FILE2);
                    proDetails.set("wens_resfile_pat_U",rectObj.getDynamicObjectCollection(RecordDetailsConstant.WENS_FILE2)); //文件
                }
                proDetails.set("wens_recpers_pat_U", item.getDynamicObject(PatrolRecordConstant.WENS_HEAD_USER));
                proDetails.set("wens_issolve_pat_U", item.getString(PatrolRecordConstant.WENS_ISSOLVE));
                proDetails.set("wens_patid_u", item.getString(PatrolRecordConstant.ID));
                if(StringUtils.equals(item.getString(PatrolRecordConstant.WENS_PATROL_RESULT),"0")){
                    ++unqualCount ;
                    ++unlineUnquCount; //非生产区不合格点位数
                }
            }
        }
        //设置区域分类数状图
        this.setTreeView(0);
        //planMap
        model.setValue("wens_plan_pat",  planMap.get("wens_plan_plan"));
        model.setValue("wens_patcom_pat",planMap.get("wens_com_plan"));
        model.setValue("wens_unqual_pat",unqualCount);//不合格位点数
        model.setValue("wens_lineunqu_pat",lineUnquCount);//不合格位点数
        model.setValue("wens_unli_unqu_pat",unlineUnquCount);//不合格位点数
        model.setValue("wens_reced_pat",recedCount);


        //清除缓存
        model.updateEntryCache(prodEntry);
        this.getView().updateView("wens_line_paten");
        model.updateEntryCache(parEntry);
        this.getView().updateView("wens_ztype_paten");
    }



    /**
     * 设置数状图
     * @param dataType
     * 0 为:巡查记录 1,为负面清单;
     */
    private void setTreeView(int dataType) {
        //父级-区域分类
        DynamicObjectCollection prodEntry = null;
        List<DynamicObject> prodEntryList = new ArrayList<>();
        if(dataType == 1){
            // 1,为负面清单;
            prodEntry = this.getModel().getEntryEntity("wens_ztype_en");
            prodEntryList = prodEntry.stream().filter(item -> item.getDynamicObject("wens_zonetype_nage") != null).collect(Collectors.toList());
        }else if(dataType == 0){
            prodEntry = this.getModel().getEntryEntity("wens_ztype_paten");
            prodEntryList = prodEntry.stream().filter(item -> item.getDynamicObject("wens_zonetype_pat") != null).collect(Collectors.toList());
        }
        if(null == prodEntry ){
            return ;
        }
        //设置数状图
        List<TreeNode> list = new ArrayList<>();
        //最上级
        TreeNode tree = new TreeNode(null, "001", "全部");
        list.add(tree);
        //清空数状图
        TreeView treeView = this.getView().getControl(TREEVIEWAP_PAT);
        if(dataType == 1) {
            // 1,为负面清单;
            treeView = this.getView().getControl(TREEVIEWAP_NEGA);
        }
        treeView.deleteAllNodes();
        for (DynamicObject item : prodEntryList) {
            DynamicObject patrolType =  null;
            if(dataType == 1) {
                // 1,为负面清单;
                patrolType = item.getDynamicObject("wens_zonetype_nage");
            }else if(dataType == 0) {
                patrolType = item.getDynamicObject("wens_zonetype_pat");
            }
            if(null == patrolType){
                continue;
            }
            //二级分类
            QFilter baseDataQFilter = QFilterUtils.getBaseDataQFilter();
            QFilter one = new QFilter("1", QCP.equals, "1");
            one.and(baseDataQFilter);
            one.and(PatrolregionConstant.ID, QCP.equals, patrolType.getPkValue());
            DynamicObject twoDynamic = BusinessDataServiceHelper.loadSingle(PatrolregionConstant.FORMBILLID, PatrolregionConstant.ALLPROPERTY, one.toArray());
            //一级分类
            DynamicObject oneDynamic = twoDynamic.getDynamicObject(PatrolregionConstant.PARENT);
            String oneId = oneDynamic.getString(PatrolregionConstant.ID);
            String oneName = oneDynamic.getString(PatrolregionConstant.NAME);
            TreeNode oneNode = new TreeNode("001", oneId, oneName);
            list.add(oneNode);
            //设置二级
            String twoId = twoDynamic.getString(PatrolregionConstant.ID);
            String twoName = twoDynamic.getString(PatrolregionConstant.NAME);
            TreeNode treeNode = new TreeNode(oneId, twoId, twoName);
            list.add(treeNode);
            treeView.addNodes(list);
            //设置默认展开
            treeView.expand("001");
            treeView.expand(twoId);
        }
        TreeNode nullTree = new TreeNode("", "", "");
        treeView.addNode(nullTree);
        treeView.focusNode(nullTree);
        treeView.deleteNode("");

    }


    /**
     * 设置区分类分录/
     * 巡查记录
     * @param item
     */
    private void setPatTypePatEntry(DynamicObject[] item) {
        DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("wens_ztype_paten");
        DynamicObjectType entryType = entryEntity.getDynamicObjectType();
        for (DynamicObject treeItem : item) {
            DynamicObject dynamicObject = new DynamicObject(entryType);
            dynamicObject.set("wens_zonetype_pat", treeItem);
            entryEntity.add(dynamicObject);
        }
    }




    /**
     * 查询巡查计划
     */
    private  void queryPlanBillData(){
        IDataModel model = this.getModel();
        model.deleteEntryData("wens_patplan_en");
        DynamicObject obj = model.getDataEntity(true);
        Date startdate = obj.getDate("wens_dateval_startdate");
        Date enddate = obj.getDate("wens_dateval_enddate");
        String org = obj.getString("wens_org.id");
        QFilter qFilter = new QFilter("org",QCP.equals,org); //z组织
        if(null != startdate && null!= enddate){
            qFilter.and("wens_startdate", QCP.less_equals, DateUtil.getDateEndTime(enddate));
            qFilter.and("wens_enddate", QCP.large_equals,DateUtil.getDateStartTime(startdate));
        }
        DynamicObjectCollection role = (DynamicObjectCollection) obj.getDynamicObjectCollection("wens_role_mul");
        if (role != null && role.size() != 0) {
            List<String> roleList = role.stream().map(item -> item.getString("fbasedataid.id")).collect(Collectors.toList());
            qFilter.and("wens_role", QCP.in, roleList);
        }

        String exestate = obj.getString("wens_exestate_head");
        if(StringUtils.isNotBlank(exestate)){
            qFilter.and("wens_exestate_head", QCP.equals, exestate);
        }
        String result = obj.getString("wens_result_query");
        if(StringUtils.isNotBlank(result)){
            qFilter.and("wens_entrydetail.wens_result", QCP.equals, result);
        }
        DynamicObjectCollection twoclass = obj.getDynamicObjectCollection("wens_twoclass");
        if(twoclass.size()>0){
            List<Object> collect = twoclass.stream().map(object -> object.get("fbasedataid.id")).collect(Collectors.toList());
            qFilter.and("wens_entrydetail.wens_two", QCP.equals, collect);
        }
        String samperiod = obj.getString("wens_samperiod");
        if(StringUtils.isNotBlank(samperiod)){
            qFilter.and("wens_samperiod", QCP.equals, samperiod);
        }
        //计划巡查位点数
        int planCount =  0;
        //已完成巡查位点数
        int comCount = 0;
        //待巡查位点数
        int planunCount = 0;
        //超期未执行位点数
        int uncomCount  = 0;
        ArrayList<String> filed = new ArrayList<>();
        filed.add(PatrolPlanConstant.BILLNO);
        filed.add(PatrolPlanConstant.ID);
        filed.add("wens_entrydetail.wens_two");
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PRODUCTLINE);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PIGSTY);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PLACE);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_THREE);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SITE);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SITEDETAILS);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_RESULT);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMPDATE);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMPUSER);
        filed.add("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO+".billno");
        filed.add("wens_exestate_head");


        DynamicObjectCollection load = QueryServiceHelper.query(PatrolPlanConstant.FORMBILLID, ToolUtils.aryToStr(filed,false), qFilter.toArray());
        DynamicObjectCollection patPlanEntry = obj.getDynamicObjectCollection("wens_patplan_en");

       for( DynamicObject planObj : load ){
//            DynamicObjectCollection planEnCol = planObj.getDynamicObjectCollection(PatrolPlanConstant.ENTRYENTITYID_WENS_ENTRYDETAIL);
//            for(DynamicObject planEn :  planEnCol){
                DynamicObject newPlanEntryObj = patPlanEntry.addNew();
////                DynamicObject newPlanEntryObj = new DynamicObject(patPlanEntry.getDynamicObjectType());
                newPlanEntryObj.set("wens_planno",planObj.getString(PatrolPlanConstant.BILLNO));
                newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_TWO,StringUtils.isNotBlank(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_TWO))?
                        BusinessDataServiceHelper.loadSingle(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_TWO),"wens_pta","id"): "");

           newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PRODUCTLINE,!StringUtils.equals(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PRODUCTLINE),"0")?
                   BusinessDataServiceHelper.loadSingle(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PRODUCTLINE),"wens_produceline","id"): "");

           newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PIGSTY,!StringUtils.equals(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PIGSTY+""),"0")?
                   BusinessDataServiceHelper.loadSingle(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PIGSTY),"wens_pigsty","id"): "");

                newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PLACE,planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_PLACE));

           newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_THREE,!StringUtils.equals(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_THREE),"0")?
                   BusinessDataServiceHelper.loadSingle(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_THREE),"wens_pta","id"): "");


           newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SITE,!StringUtils.equals(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SITE),"0")?
                   BusinessDataServiceHelper.loadSingle(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SITE),"wens_pats","id"): "");

                newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SITEDETAILS,planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SITEDETAILS));

                newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_RESULT,planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_RESULT));
                newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMPDATE,planObj.getDate("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMPDATE));

           newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMPUSER,!StringUtils.equals(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMPUSER),"0")?
                   BusinessDataServiceHelper.loadSingle(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMPUSER),"bos_user","id"): "");
                newPlanEntryObj.set(PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO,planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO+".billno"));
                newPlanEntryObj.set("wens_billid", planObj.getString(PatrolPlanConstant.ID) );
//                patPlanEntry.add(newPlanEntryObj);

                //计算数据;
                //计划巡查位点数
                ++planCount;
                //已完成巡查位点数
                if(!ObjectUtil.isNull(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO+".billno"))){
                    ++comCount;
                }
                //待巡查位点数
                if(StringUtils.equals(planObj.getString("wens_exestate_head"),EnvPlanExeStatusEnum.EXEING.getValue()) &&
                        ObjectUtil.isNull(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO+".billno"))){
                    ++planunCount;
                }
                //超期未执行位点数
                if(StringUtils.equals(planObj.getString("wens_exestate_head"),EnvPlanExeStatusEnum.UNCOM.getValue()) &&
                        ObjectUtil.isNull(planObj.getString("wens_entrydetail."+PatrolPlanConstant.WENS_ENTRYDETAIL_WENS_SAMBILLNO+".billno"))){
                    ++uncomCount;
                }
//          }
        }
        model.setValue("wens_plan_plan",planCount);
        model.setValue("wens_com_plan",comCount);
        model.setValue("wens_planun_plan",planunCount);
        model.setValue("wens_planuncom_plan",uncomCount);
        model.updateEntryCache(patPlanEntry);
        this.getView().updateView("wens_patplan_en");
    }


    /**
     * 整改记录查询
     */
    private  void queryRecordDetailsData(){
        IDataModel model = this.getModel();
        model.deleteEntryData("wens_recorddetails_en");
        DynamicObject obj = model.getDataEntity(true);
        String org = obj.getString("wens_org.id");
        QFilter qFilter = new QFilter("org",QCP.equals,org); //组织
        Date startdate = obj.getDate("wens_startdateval_rect");
        Date enddate = obj.getDate("wens_enddateval_rect");
        if(null != startdate && null!= enddate){
            qFilter.and("wens_businessdate", QCP.large_equals, DateUtil.getDateStartTime(startdate));
            qFilter.and("wens_businessdate", QCP.less_equals,DateUtil.getDateEndTime(enddate));
        }
        //巡查小组
        DynamicObject role = obj.getDynamicObject("wens_rolequery_rect");
        if(null!= role){
            qFilter.and("wens_inspectionteam", QCP.equals, role.getPkValue());
        }
        String exestate = obj.getString("wens_statusquery_rect");
        if(StringUtils.isNotBlank(exestate)){
            qFilter.and("billstatus", QCP.equals, exestate);
        }
        //审批结果
        String result = obj.getString("wens_resultquery_rect");
        if(StringUtils.isNotBlank(result)){
            if(StringUtils.equals("1",result)){
                qFilter.and(new QFilter("wens_issolve", QCP.equals, result).
                        or("wens_issolve", QCP.equals, "").or("wens_issolve", QCP.is_null, null));
            }else{
                qFilter.and("wens_issolve", QCP.equals, result);
            }

        }

        DynamicObject[] load = BusinessDataServiceHelper.load(RecordDetailsConstant.FORMBILLID, RecordDetailsConstant.ALLPROPERTY, qFilter.toArray());
        DynamicObjectCollection patPlanEntry = obj.getDynamicObjectCollection("wens_recorddetails_en");
        for( DynamicObject queryObj : load ) {
            DynamicObject newPlanEntryObj = new DynamicObject(patPlanEntry.getDynamicObjectType());
            newPlanEntryObj.set("wens_result_rect",       queryObj.getString(RecordDetailsConstant.WENS_AUDITRESULT));
            newPlanEntryObj.set("wens_negativebill_rect", queryObj.getString(RecordDetailsConstant.WENS_NEGATIVELIST+".billno"));
            newPlanEntryObj.set("wens_two_rect",          queryObj.getDynamicObject(RecordDetailsConstant.WENS_CLASSTWO));
            newPlanEntryObj.set("wens_productline_rect" , queryObj.getDynamicObject(RecordDetailsConstant.WENS_PRODUCELINE));
            newPlanEntryObj.set("wens_pigsty_rect",       queryObj.getDynamicObject(RecordDetailsConstant.WENS_PIGDORMITORY));
            newPlanEntryObj.set("wens_place_rect",        queryObj.getString(RecordDetailsConstant.WENS_FIELD));
            newPlanEntryObj.set("wens_three_rect",        queryObj.getDynamicObject(RecordDetailsConstant.WENS_REGIONTYPE));
            newPlanEntryObj.set("wens_site_rect",         queryObj.getDynamicObject(RecordDetailsConstant.WENS_INSPECTIONSITE));
            newPlanEntryObj.set("wens_sitedetails_rect",  queryObj.getString(RecordDetailsConstant.WENS_LOCATION));
            newPlanEntryObj.set("wens_desc_rect",         queryObj.getString(RecordDetailsConstant.WENS_PROBLEM));
//            newPlanEntryObj.set("wens_problemimage1",     queryObj.getString(RecordDetailsConstant.WENS_PROBLEMIMAGE1));
//            newPlanEntryObj.set("wens_problemimage2",     queryObj.getString(RecordDetailsConstant.WENS_PROBLEMIMAGE2));
//            newPlanEntryObj.set("wens_problemimage3",     queryObj.getString(RecordDetailsConstant.WENS_PROBLEMIMAGE3));
//            newPlanEntryObj.set("wens_resultphoto1",      queryObj.getString(RecordDetailsConstant.WENS_RESULTPHOTO1));
//            newPlanEntryObj.set("wens_resultphoto2",      queryObj.getString(RecordDetailsConstant.WENS_RESULTPHOTO2));
//            newPlanEntryObj.set("wens_resultphoto3",      queryObj.getString(RecordDetailsConstant.WENS_RESULTPHOTO3));
            newPlanEntryObj.set("wens_exedate_rect",      queryObj.getDate(RecordDetailsConstant.WENS_BUSINESSDATE));
            newPlanEntryObj.set("wens_measures",          queryObj.getString(RecordDetailsConstant.WENS_MEASURES));
            newPlanEntryObj.set("wens_completiondate",    queryObj.getDate(RecordDetailsConstant.WENS_COMPLETIONDATE));
            newPlanEntryObj.set("wens_exeperson_rect",    queryObj.getDynamicObject(RecordDetailsConstant.WENS_EXECUTOR));
            newPlanEntryObj.set("wens_billno_rect",       queryObj.getString(RecordDetailsConstant.BILLNO));
            newPlanEntryObj.set("wens_id_rect",           queryObj.getString(RecordDetailsConstant.ID));
            newPlanEntryObj.set("wens_issolve_rect",      queryObj.getString(RecordDetailsConstant.WENS_ISSOLVE));
            fileToImage(queryObj,newPlanEntryObj);
            file2ToImage(queryObj,newPlanEntryObj);
            patPlanEntry.add(newPlanEntryObj);
        }
        model.updateEntryCache(patPlanEntry);
        this.getView().updateView("wens_recorddetails_en");
    }


    //设置图片,由于整改记录数据库中未存放图片链接...
    private void fileToImage(DynamicObject queryObj,DynamicObject newPlanEntryObj) {
        int i = 1;
        DynamicObjectCollection fileCol = queryObj.getDynamicObjectCollection("wens_file1");
        String[] upLoadImg = new String[]{".png", ".jpeg", ".jpg"};
        for(DynamicObject fileObj: fileCol) {
            if(i>3){
                break;
            }
            String  fileName = ToolUtils.cnulls(fileObj.getString("fbasedataid.name"));
            List<String> list = Arrays.stream(upLoadImg).filter(a -> fileName.endsWith(a)).collect(Collectors.toList());
            if(list.size()>0){
                newPlanEntryObj.set("wens_problemimage" + i, fileObj.getString("fbasedataid.url"));
            }
            ++i;
        }
    }
    private void file2ToImage(DynamicObject queryObj,DynamicObject newPlanEntryObj) {
        int i = 1;
        DynamicObjectCollection fileCol = queryObj.getDynamicObjectCollection("wens_file2");
        String[] upLoadImg = new String[]{".png", ".jpeg", ".jpg"};
        for(DynamicObject fileObj: fileCol) {
            if(i>3){
                break;
            }
            String  fileName = ToolUtils.cnulls(fileObj.getString("fbasedataid.name"));
            List<String> list = Arrays.stream(upLoadImg).filter(a -> fileName.endsWith(a)).collect(Collectors.toList());
            if(list.size()>0){
                newPlanEntryObj.set("wens_resultphoto" + i, fileObj.getString("fbasedataid.url"));
            }
            ++i;
        }
    }





    /**
     * 查询整改计划
     */
    private  void queryRectPlanData(){
        IDataModel model = this.getModel();
        model.deleteEntryData("wens_rectplan_en");
        DynamicObject obj = model.getDataEntity(true);
        String org = obj.getString("wens_org.id");
        QFilter qFilter = new QFilter("org",QCP.equals,org); //z组织
        Date startdate = obj.getDate("wens_startdateval_rectpl");
        Date enddate = obj.getDate("wens_enddateval_rectpl");
        if(null != startdate && null!= enddate){
            qFilter.and("wens_businessdate", QCP.large_equals, DateUtil.getDateStartTime(startdate));
            qFilter.and("wens_businessdate", QCP.less_equals,DateUtil.getDateEndTime(enddate));
        }
        //巡查小组
        DynamicObject role = obj.getDynamicObject("wens_rolequery_rectpl");
        if(null!= role){
            qFilter.and("wens_inspectionteam", QCP.equals, role.getPkValue());
        }
        //单据状态
        String billstatus  = obj.getString("wens_statusquery_rectpl");
        if(StringUtils.isNotBlank(billstatus)){
            qFilter.and("billstatus", QCP.equals, billstatus);
        }
        //执行状态
        String exestate = obj.getString("wens_exestatequery_rectpl");
        if(StringUtils.isNotBlank(exestate)){
            qFilter.and("wens_planstart", QCP.equals, exestate);
        }
        String orderby = "wens_businessdate desc";
        DynamicObject[] load = BusinessDataServiceHelper.load(PlanDetailsConstant.FORMBILLID, PlanDetailsConstant.ALLPROPERTY, qFilter.toArray(),orderby);
        DynamicObjectCollection entryCol = obj.getDynamicObjectCollection("wens_rectplan_en");
        for( DynamicObject queryObj : load ){
            DynamicObject newPlanEntryObj = new DynamicObject(entryCol.getDynamicObjectType());
            newPlanEntryObj.set("wens_negativebill_rectpl", queryObj.getString(PlanDetailsConstant.WENS_NEGATIVELIST+".billno"));
            newPlanEntryObj.set("wens_pigsty_rectpl",       queryObj.getDynamicObject(PlanDetailsConstant.WENS_PIGDORMITORY));
            newPlanEntryObj.set("wens_place_rectpl",        queryObj.getString(PlanDetailsConstant.WENS_FIELD));
            newPlanEntryObj.set("wens_three_rectpl",        queryObj.getDynamicObject(PlanDetailsConstant.WENS_REGIONTYPE));
            newPlanEntryObj.set("wens_site_rectpl",         queryObj.getDynamicObject(PlanDetailsConstant.WENS_INSPECTIONSITE));
            newPlanEntryObj.set("wens_sitedetails_rectpl",  queryObj.getString(PlanDetailsConstant.WENS_LOCATION));
            newPlanEntryObj.set("wens_samuser_rectpl",      queryObj.getDynamicObject(PlanDetailsConstant.WENS_INSPECTIONMAN));
            newPlanEntryObj.set("wens_result_rectpl",       queryObj.getString(PlanDetailsConstant.WENS_INSPECTIONRESULTS));
            newPlanEntryObj.set("wens_desc_rectpl",         queryObj.getString(PlanDetailsConstant.WENS_PROBLEM));
            newPlanEntryObj.set("wens_exedate_rectpl",      queryObj.getDate(PlanDetailsConstant.WENS_COMPLETIONDATE));
            newPlanEntryObj.set("wens_exeperson_rectpl",    queryObj.getDynamicObject(PlanDetailsConstant.WENS_PLANRESPONPER));
            entryCol.add(newPlanEntryObj);
        }
        model.updateEntryCache(entryCol);
        this.getView().updateView("wens_rectplan_en");
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        super.afterDoOperation(e);
        FormOperate formOperate = (FormOperate) e.getSource();
        String operateKey = formOperate.getOperateKey();
        ////////////////////////////////////////////////////巡查计划///////////////////////
        if(StringUtils.equals( operateKey ,"querypatrolplan")){
            this.getModel().deleteEntryData("wens_patplan_en");
            queryPlanBillData();
        }else if(StringUtils.equals( operateKey ,"plancancel")){
            IDataModel model = this.getModel();
            EntryGrid   patplanEn  = this.getControl("wens_patplan_en");
            DynamicObjectCollection patplanCol = this.getModel().getDataEntity().getDynamicObjectCollection("wens_patplan_en");
            int[] selectRows = patplanEn.getSelectRows();
            if(selectRows.length == 0){
                this.getView().showTipNotification("请选择需要操作的数据!",5000);
//                e.setCancel(true);
                return;
            }
            HashSet<Object> billIds = new HashSet<>();
            for(int ii : selectRows){
                DynamicObject entity = patplanCol.get(ii);
                billIds.add(entity.getString("wens_billid"));
            }
            QFilter billQFilter = QFilterUtils.getBillQFilter();
            billQFilter.and("id",QCP.in,billIds);
            DynamicObject[] load = BusinessDataServiceHelper.load(PatrolPlanConstant.FORMBILLID, PatrolPlanConstant.ALLPROPERTY, billQFilter.toArray());
            if(load.length == 0){
                this.getView().showTipNotification("选择的数据无效!",5000);
//                e.setCancel(true);
            }
            OperateOption operateOption = OperateOption.create();
            operateOption.setVariableValue(OperateOptionConst.ISHASRIGHT, String.valueOf(true));
            OperationResult operationResult = OperationServiceHelper.executeOperate("cancelplan", PatrolPlanConstant.FORMBILLID, load, operateOption);
            if(operationResult.isSuccess()){
                this.getView().showSuccessNotification("操作成功!",3);
            }else{
                String  error = "";
                if (operationResult.getMessage() != null) {
                    error = operationResult.getMessage() + " ";
                }
                if (operationResult.getAllErrorOrValidateInfo().size() > 0) {
                    error = error + operationResult.getAllErrorOrValidateInfo().get(0).getMessage();
                }
                this.getView().showTipNotification(error);
            }
        }
        /////////////////////////////////巡查记录///////////////////////////////
        //巡查记录查询
        else if(StringUtils.equals( operateKey ,"wens_query_pat")){
            Tab tabap = this.getControl("wens_tabap_pat");
            String currentTab = tabap.getCurrentTab();
            setVisibleTab(currentTab);
            this.getModel().deleteEntryData("wens_line_paten");
            this.getModel().deleteEntryData("wens_ztype_paten");
            queryPatrolList(null);
        }
        //审核
        else if(StringUtils.equals( operateKey ,"wens_audit_pat")){
            doOptionPatBill("submit");
        }
        //删除
        else if(StringUtils.equals( operateKey ,"wens_del_pat")) {
            ApiResult apiResult = doOptionPatBill("delete");
            if (apiResult.getSuccess()) {
                queryPatrolList(null);
//                Tab tabap = this.getControl("wens_tabap_pat");
//                String tabKey = tabap.getCurrentTab();
//                //巡查记录
//                if ("wens_tabpageap_pat1".equals(tabKey)) {
//                    DynamicObjectCollection towEntCol = this.getModel().getDataEntity(true).getDynamicObjectCollection("wens_line_pat");
//                    EntryGrid twoEntry = this.getControl("wens_line_pat");
//                    int[] twoSelects = twoEntry.getSelectRows();
//                    if(twoSelects.length>0){
//                        int twoSelect = twoSelects[0];
//                        DynamicObject twoObj = towEntCol.get(twoSelect);
//                        DynamicObjectCollection  patsuben = twoObj.getDynamicObjectCollection("wens_line_patsuben");
//                        EntryGrid suben = this.getControl("wens_line_patsuben");
//                        int[] selects = suben.getSelectRows();
//                        List<Integer> selectRows = Arrays.stream(selects).boxed().collect(Collectors.toList());
//                        ArrayList<DynamicObject> newEntryCol = new ArrayList<>();
//                        DynamicObject[] dataEntitys = suben.getEntryData().getDataEntitys();
//                        for(int j = 0; j<dataEntitys.length;j++){
//                            if(!selectRows.contains(j)){
//                                newEntryCol.add(dataEntitys[j]);
//                            }
//                        }
//                        twoObj.set("wens_line_patsuben",newEntryCol.toArray(new DynamicObject[newEntryCol.size()]));
//                    }
//                    this.getModel().updateEntryCache(towEntCol);
//                    this.getView().updateView("wens_line_patsuben");
//                } else if ("wens_tabpageap_pat2".equals(tabKey)) {
//                    DynamicObjectCollection towEntCol = this.getModel().getDataEntity(true).getDynamicObjectCollection("wens_ztype_paten");
//                    EntryGrid suben = this.getControl("wens_uline_patsuben");
//                    int[] selects = suben.getSelectRows();
//                    List<Integer> selectRows = Arrays.stream(selects).boxed().collect(Collectors.toList());
//                    ArrayList<DynamicObject> newEntryCol = new ArrayList<>();
//                    EntryData entryData = suben.getEntryData();
//                    DynamicObject[] dataEntitys = suben.getEntryData().getDataEntitys();
//                    for(int j = 0; j<dataEntitys.length;j++){
//                        if(!selectRows.contains(j)){
//                            newEntryCol.add(dataEntitys[j]);
//                        }
//                    }
//                    entryData.setDataEntitys(newEntryCol.toArray(new DynamicObject[newEntryCol.size()]));
//                }
            }
        }
        //新增
        else if(StringUtils.equals( operateKey ,"wens_add_pat")){
            showForm("wens_patrol_record_add","巡查记录新增");
        }
        //反审核
        else if(StringUtils.equals( operateKey ,"wens_unaudit_pat")){
            doOptionPatBill("unaudit");

        }
        //已整改
        else if(StringUtils.equals( operateKey ,"wens_rectified_pat")){
            Tab tabap = this.getControl("wens_tabap_pat");
            String currentTab = tabap.getCurrentTab();
            setVisibleTab(currentTab);
            HashMap<Object, Object> objectObjectHashMap = new HashMap<>();
            objectObjectHashMap.put("rectified",true);
            queryPatrolList(objectObjectHashMap);
        }
        ///////////////////////////////////////////////////////负面清单//////////////////////////
        //负面清单查询
        else if(StringUtils.equals( operateKey ,"wens_query_nage")){
            Tab tabap = this.getControl("wens_tabap_nega");
            String currentTab = tabap.getCurrentTab();
            setVisibleTab(currentTab);
            this.getModel().deleteEntryData("wens_line_nageen");
            this.getModel().deleteEntryData("wens_ztype_en");
            queryNegativeList();
        }
        // wens_query_rectpl 整改计划////////////////////////////////////////////////////////////////////
        else if(StringUtils.equals( operateKey ,"wens_query_rectpl")){
            this.getModel().deleteEntryData("wens_rectplan_en");
            queryRectPlanData();
        }
        /////////////////////////////////////////////整改记录////////////////////////////
        //整改记录查询
        else if(StringUtils.equals( operateKey ,"wens_query_rectify")){
            this.getModel().deleteEntryData("wens_recorddetails_en");
            queryRecordDetailsData();
        }
        //审核
        else if(StringUtils.equals( operateKey ,"wens_audit_rectify")){
            doOptionRectifyBill("audit");
        }
        //删除
        else if(StringUtils.equals( operateKey ,"wens_del_rectify")) {
            ApiResult apiResult = doOptionRectifyBill("delete");
            if(apiResult.getSuccess()){
                //删除后调用查询刷新数据;
                queryRecordDetailsData();
            }

        }
        //新增
        else if(StringUtils.equals( operateKey ,"wens_add_rectify")){
            showForm("wens_recordenter","整改记录新增");
        }
        //反审核
        else if(StringUtils.equals( operateKey ,"wens_unaudit_rectify")){
            doOptionRectifyBill("unaudit");
        }
        /////////////////////////////////////////////整改记录///////////////////


    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs e) {
        super.beforeDoOperation(e);

    }


    /**
     * 展示页面;
     * @param
     */
    private  void  showForm(String  billFid,String  billName){
        // 创建弹出页面对象，FormShowParameter表示弹出页面为动态表单
        FormShowParameter showParameter = new FormShowParameter();
        // 设置弹出页面的编码
        showParameter.setFormId(billFid);
        // 设置弹出页面标题
        showParameter.setCaption(billName);
        // CloseCallBack参数：回调插件，回调标识
        showParameter.setCloseCallBack(new CloseCallBack(this, billFid));
        // 设置弹出页面打开方式，支持模态，新标签等
        showParameter.getOpenStyle().setShowType(ShowType.Modal);
        showParameter.setCustomParam("orgIdStr",this.getModel().getDataEntity(true).getString("wens_org.id"));
        showParameter.setCustomParam("cusaddnew",true);
        // 弹出页面对象赋值给父页面
        this.getView().showForm(showParameter);
    }


    /**
     * 巡查记录操作方法
     * 审核,反审核;
     * @param opType
     */
    private ApiResult  doOptionPatBill(String opType){
        ArrayList<DynamicObject> arrayList = getSelectPatData(1,opType);
        if(null == arrayList){
            return ApiResult.fail(null);
        }
        if(arrayList.size() > 0){
            OperationResult operationResult = OperationServiceHelper.executeOperate(opType,
                    PatrolRecordConstant.FORMBILLID,arrayList.toArray(new DynamicObject[arrayList.size()]),OperateOption.create());
            if(!operationResult.isSuccess()){
                String  error = "";
                if (operationResult.getMessage() != null) {
                    error = operationResult.getMessage() + " ";
                }
                if (operationResult.getAllErrorOrValidateInfo().size() > 0) {
                    error = error + operationResult.getAllErrorOrValidateInfo().get(0).getMessage();
                }
                this.getView().showErrorNotification(error);
                return ApiResult.fail(null);
            }else{
                this.getView().showSuccessNotification("操作成功!");
                return ApiResult.success(null);
            }
        }
        return ApiResult.fail(null);
    }


    /**
     * 巡查记录操作方法
     * 审核,反审核;
     * @param opType
     */
    private ApiResult  doOptionRectifyBill(String opType){
        ArrayList<DynamicObject> arrayList = getSelectRectifyData(1,opType);
        if(null == arrayList){
            return ApiResult.fail(null);
        }
        if(arrayList.size() > 0){
            OperationResult operationResult = null;
            if(StringUtils.equals("audit",opType)){
                ArrayList<DynamicObject> saveObj = new ArrayList<>();
                ArrayList<DynamicObject> submitObj = new ArrayList<>();
                for(DynamicObject object:arrayList) {
                    if (StringUtils.equals(object.getString(RecordDetailsConstant.BILLSTATUS),
                            BillStatusEnum.SAVE)) {
                        saveObj.add(object);
                    } else if (StringUtils.equals(object.getString(RecordDetailsConstant.BILLSTATUS),
                            BillStatusEnum.SUBMIT)) {
                        submitObj.add(object);
                    }
                }
                //如果是暂存的数据;
                if(saveObj.size()>0){
                    operationResult = OperationServiceHelper.executeOperate("submit",
                            RecordDetailsConstant.FORMBILLID,saveObj.toArray(new DynamicObject[saveObj.size()]),OperateOption.create());
                    if(operationResult.isSuccess()){
                        operationResult = OperationServiceHelper.executeOperate("audit",
                                RecordDetailsConstant.FORMBILLID,saveObj.toArray(new DynamicObject[saveObj.size()]),OperateOption.create());
                        if(!operationResult.isSuccess()){
                            setErrorMsg(operationResult);
                            return ApiResult.fail(null);
                        }else{
                            this.getView().showSuccessNotification("操作成功!");
                            return ApiResult.success(null);
                        }
                    }else{
                        setErrorMsg(operationResult);
                        return ApiResult.fail(null);
                    }
                }
                //如果是提交的数据;
                if(submitObj.size()>0){
                    operationResult = OperationServiceHelper.executeOperate("audit",
                            RecordDetailsConstant.FORMBILLID,submitObj.toArray(new DynamicObject[submitObj.size()]),OperateOption.create());
                    if(!operationResult.isSuccess()){
                        setErrorMsg(operationResult);
                        return ApiResult.fail(null);
                    }else{
                        this.getView().showSuccessNotification("操作成功!");
                        return ApiResult.success(null);
                    }
                }

            }else{
                 operationResult = OperationServiceHelper.executeOperate(opType,
                        RecordDetailsConstant.FORMBILLID,arrayList.toArray(new DynamicObject[arrayList.size()]),OperateOption.create());
                if(!operationResult.isSuccess()){
                    setErrorMsg(operationResult);
                    return ApiResult.fail(null);
                }else{
                    this.getView().showSuccessNotification("操作成功!");
                    return ApiResult.success(null);
                }
            }
        }
        return ApiResult.fail(null);
    }

private void setErrorMsg(OperationResult operationResult){
    String  error = "";
    if (operationResult.getMessage() != null) {
        error = operationResult.getMessage() + " ";
    }
    if (operationResult.getAllErrorOrValidateInfo().size() > 0) {
        error = error + operationResult.getAllErrorOrValidateInfo().get(0).getMessage();
    }
    this.getView().showErrorNotification(error);
}

    /**
     * 获取选择的整改记录
     * 需返回的数据类型, 0为id, 1为对象;
     * opType 操作类型
     * @return
     */
    private  ArrayList  getSelectRectifyData(int dataType,String opType){
        ArrayList  arrayList = new  ArrayList<>();
        boolean flag = true;
        StringBuilder sbu = new StringBuilder();
        sbu.append("第");
        //整改记录
        EntryGrid suben = this.getControl("wens_recorddetails_en");
        int[] selectRows = suben.getSelectRows();
        if(selectRows.length == 0){
            this.getView().showTipNotification("请选择要操作的数据!");
        }
        DynamicObject[] dataEntitys = suben.getEntryData().getDataEntitys();
        for(int ii :selectRows){
            DynamicObject dataEntity = dataEntitys[ii];
            String  patid = dataEntity.getString("wens_id_rect");
            if( dataType == 0 ) {
                arrayList.add(patid);
            }else {
                DynamicObject object = BusinessDataServiceHelper.loadSingle(patid, RecordDetailsConstant.FORMBILLID);
                String billStatus = object.getString(RecordDetailsConstant.BILLSTATUS);
                if(StringUtils.equals(opType, "submit") || StringUtils.equals(opType, "audit") ){
                    if(StringUtils.equals(billStatus,BillStatusEnum.AUDIT)){
                        flag = false;
                        sbu.append(" "+(ii+1)+" ");
                    }
                }else if(StringUtils.equals(opType, "delete") ){
                    if(!StringUtils.equals(billStatus,BillStatusEnum.SAVE)){
                        flag = false;
                        sbu.append(" "+(ii+1)+" ");
                    }
                }else if(StringUtils.equals(opType, "unaudit")) {
                    if (!StringUtils.equals(billStatus, BillStatusEnum.AUDIT)) {
                        flag = false;
                        sbu.append(" " + (ii+1) + " ");
                    }
                }
                arrayList.add(object);
            }
        }

        sbu.append("行");
        if(!flag){
            if(StringUtils.equals(opType, "submit") || StringUtils.equals(opType, "audit")  || StringUtils.equals(opType, "delete") ){
                this.getView().showErrorNotification(sbu.toString()+",已审核,不能进行此操作,请先取消勾选!");
                return null;
            }else if(StringUtils.equals(opType, "unaudit")){
                this.getView().showErrorNotification(sbu.toString()+",未审核,不能进行此操作,请先取消勾选!");
                return null;
            }
        }
        return arrayList;
    }

    /**
     * 获取选择的巡查记录
     * 需返回的数据类型, 0为id, 1为对象;
     * opType 操作类型
     * @return
     */
    private  ArrayList  getSelectPatData(int dataType,String opType){
        ArrayList  arrayList = new  ArrayList<>();
        Tab tabap = this.getControl("wens_tabap_pat");
        String tabKey = tabap.getCurrentTab();
        boolean flag = true;
        StringBuilder sbu = new StringBuilder();
        sbu.append("第");
        //巡查记录
        if ("wens_tabpageap_pat1".equals(tabKey)) {
            EntryGrid suben = this.getControl("wens_line_patsuben");
            int[] selectRows = suben.getSelectRows();
            if(selectRows.length == 0){
                this.getView().showTipNotification("请选择要操作的数据!");
            }
            DynamicObject[] dataEntitys = suben.getEntryData().getDataEntitys();
            for(int ii :selectRows){
                DynamicObject dataEntity = dataEntitys[ii];
                String  patid = dataEntity.getString("wens_patid");
                if( dataType == 0 ) {
                    arrayList.add(patid);
                }else {
                    DynamicObject object = BusinessDataServiceHelper.loadSingle(patid, PatrolRecordConstant.FORMBILLID);
                    String billStatus = object.getString(PatrolRecordConstant.BILLSTATUS);
                    if(StringUtils.equals(opType, "audit") || StringUtils.equals(opType, "delete") ){
                        if(!StringUtils.equals(billStatus,BillStatusEnum.SAVE)){
                            flag = false;
                            sbu.append(" "+(ii+1)+" ");
                        }
                    }else if(StringUtils.equals(opType, "unaudit")) {
                        if (!StringUtils.equals(billStatus, BillStatusEnum.AUDIT)) {
                            flag = false;
                            sbu.append(" " + (ii+1) + " ");
                        }
                    }
                    arrayList.add(object);
                }
            }

        }else if ("wens_tabpageap_pat2".equals(tabKey)) {
            EntryGrid suben = this.getControl("wens_uline_patsuben");
            int[] selectRows = suben.getSelectRows();
            if(selectRows.length == 0){
                this.getView().showTipNotification("请选择要操作的数据!");
            }
            DynamicObject[] dataEntitys = suben.getEntryData().getDataEntitys();
            for(int ii :selectRows){
                DynamicObject dataEntity = dataEntitys[ii];
                String patid = dataEntity.getString("wens_patid_u");
                if( dataType == 0 ) {
                    arrayList.add(patid);
                }else {
                    DynamicObject object = BusinessDataServiceHelper.loadSingle(patid, PatrolRecordConstant.FORMBILLID);
                    String billStatus = object.getString(PatrolRecordConstant.BILLSTATUS);
                    if(StringUtils.equals(opType, "audit") || StringUtils.equals(opType, "delete") ){
                        if(!StringUtils.equals(billStatus,BillStatusEnum.SAVE)){
                            flag = false;
                            sbu.append(" "+(ii+1)+" ");
                        }
                    }else if(StringUtils.equals(opType, "unaudit")) {
                        if (!StringUtils.equals(billStatus, BillStatusEnum.AUDIT)) {
                            flag = false;
                            sbu.append(" " + (ii+1) + " ");
                        }
                    }
                    arrayList.add(object);
                }
            }
        }
        sbu.append("行");
        if(!flag){
            if(StringUtils.equals(opType, "audit") || StringUtils.equals(opType, "delete") ){
                this.getView().showTipNotification(sbu.toString()+",已审核,不能进行此操作,请先取消勾选!");
                return null;
            }else if(StringUtils.equals(opType, "unaudit")){
                this.getView().showTipNotification(sbu.toString()+",未审核,不能进行此操作,请先取消勾选!");
                return null;
            }
        }
        return arrayList;
    }


    @Override
    public void beforeF7Select(BeforeF7SelectEvent evt) {
        BasedataEdit source = (BasedataEdit) evt.getSource();
        ListShowParameter formShowParameter = (ListShowParameter) evt.getFormShowParameter();
        List<QFilter> filters = formShowParameter.getListFilterParameter().getQFilters();
        DynamicObject org = this.getModel().getDataEntity(true).getDynamicObject("wens_org");
        if ("wens_role".equals(source.getKey()) || "wens_role_mul".equals(source.getKey())
                ||  "wens_rolequery_pat".equals(source.getKey())
                ||  "wens_rolequery_nage".equals(source.getKey())
                || "wens_rolequery_rectpl".equals(source.getKey())
                || "wens_rolequery_rect".equals(source.getKey()))
        {
            QFilter qFilters = QFilterUtils.getBaseDataQFilter();
            qFilters.and("wens_org",QCP.equals,org.getPkValue());
            qFilters.and("wens_gtype",QCP.equals,"0");//yang严密闭
            filters.add(qFilters);
        }else if("wens_twoclass".equals(source.getKey())){
            QFilter qFilters = QFilterUtils.getBaseDataQFilter();
            qFilters.and(new QFilter("level", QCP.equals, "2"));
            filters.add(qFilters);
        }
    }

    @Override
    public void tabSelected(TabSelectEvent tabSelectEvent) {
        String tabKey = tabSelectEvent.getTabKey();
        setVisibleTab(tabKey);
//
//        if(StringUtils.equals(tabKey,"wens_tabpageap2")){
//            Tab control = this.getControl("wens_tabap_pat");
//            setVisableTab(control.getCurrentTab());
//        }else if(StringUtils.equals(tabKey,"wens_tabpageap3")){
//
//        }else{
//
//        }
    }

    private  void  setVisibleTab(String tabKey){
        if("wens_tabpageap1".equals(tabKey)){
            this.getView().setVisible(true, "wens_flex_plan");
            this.getView().setVisible(false, new String[] {"wens_flex_pat","wens_flex_nage"});
        }else if("wens_tabpageap2".equals(tabKey)){
            Tab control = this.getControl("wens_tabap_pat");
            setVisibleTab(control.getCurrentTab());
        }else if("wens_tabpageap3".equals(tabKey)){
            Tab control = this.getControl("wens_tabap_nega");
            setVisibleTab(control.getCurrentTab());
            this.getView().setVisible(false, new String[] {"wens_flex_plan"});
        }else if("wens_tabpageap4".equals(tabKey)){
//            this.getView().setVisible(true, new String[] {"wens_flex_nage"});
            this.getView().setVisible(false, new String[] {"wens_flex_plan","wens_flex_pat","wens_flex_nage"});
        }else if("wens_tabpageap5".equals(tabKey)){
//            this.getView().setVisible(true, new String[] {"wens_flex_nage"});
            this.getView().setVisible(false, new String[] {"wens_flex_plan","wens_flex_pat","wens_flex_nage"});
        }else if ("wens_tabpageap_nega1".equals(tabKey)) { //负面清单
            this.getView().setVisible(true, new String[] {"wens_advconap1"});
            this.getView().setVisible(false, new String[] {"wens_advconap2","wens_flex_pat","wens_flex_nage","wens_flex_plan"});
        } else if ("wens_tabpageap_nega2".equals(tabKey)) {//负面清单
            this.getView().setVisible(true, new String[] {"wens_advconap2"});
            this.getView().setVisible(false, new String[] {"wens_advconap1","wens_flex_pat","wens_flex_nage","wens_flex_plan"});
        }else if ("wens_tabpageap_pat1".equals(tabKey)) {//巡查记录
            this.getView().setVisible(true, new String[] {"wens_advconap11","wens_flex_pat"});
            this.getView().setVisible(false, new String[] {"wens_advconap21","wens_flex_plan","wens_flex_nage"});
        }else if ("wens_tabpageap_pat2".equals(tabKey)) {//巡查记录
            this.getView().setVisible(true, new String[] {"wens_advconap21","wens_flex_pat"});
            this.getView().setVisible(false, new String[] {"wens_advconap11","wens_flex_plan","wens_flex_nage"});
        }
    }


    @Override
    public void treeNodeClick(TreeNodeEvent evt) {
        TreeView source = (TreeView) evt.getSource();
        Object nodeId = evt.getNodeId();
        QFilter filter = new QFilter(PatrolregionConstant.ID, QCP.equals, nodeId);
        DynamicObject ptaData = BusinessDataServiceHelper.loadSingle(PatrolregionConstant.FORMBILLID, filter.toArray());
        if (ptaData != null) {
            String level = ptaData.getString(PatrolregionConstant.LEVEL);
            if(StringUtils.equals(source.getKey(),"wens_treeviewap_pat")){
                if ("2".equals(level)) {
                    //点击区分分录
                    DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("wens_ztype_paten");
                    Optional<Integer> first = entryEntity.stream().filter(item ->
                            StringUtil.equals(String.valueOf(nodeId), item.getDynamicObject("wens_zonetype_pat").getString("id")))
                            .map(entryEntity::indexOf)
                            .findFirst();
                    if (first.isPresent()) {
                        Integer integer = first.get();
                        EntryGrid control = getControl("wens_ztype_paten");
                        control.selectRows(integer);
                    }
                } else {
                    //取消选择
                    EntryGrid control = getControl("wens_ztype_paten");
                    control.selectRows(-1);
                }
            }else if(StringUtils.equals(source.getKey(),"wens_treeviewap_nega")){
                if ("2".equals(level)) {
                    //点击区分分录
                    DynamicObjectCollection entryEntity = this.getModel().getEntryEntity("wens_ztype_en");
                    Optional<Integer> first = entryEntity.stream().filter(item ->
                            StringUtil.equals(String.valueOf(nodeId), item.getDynamicObject(WENS_PATROL_TYPE_ENTRY).getString("id")))
                            .map(entryEntity::indexOf)
                            .findFirst();
                    if (first.isPresent()) {
                        Integer integer = first.get();
                        EntryGrid control = getControl("wens_ztype_en");
                        control.selectRows(integer);
                    }
                } else {
                    //取消选择
                    EntryGrid control = getControl("wens_ztype_en");
                    control.selectRows(-1);
                }
            }
        }
    }


    @Override
    public void hyperLinkClick(HyperLinkClickEvent hyperLinkClickEvent) {

    }
}
